/*
 * Removes spaces ' ' from files.
 * Copyright (C) 2010  Ruslan Mikhaylenko
 */

#include <sys/types.h>
#include <dirent.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

int has_spaces(char *name)
{
	for(int i=0; i<strlen(name); i++)
	if(name[i] == ' ') return 1;
	return 0;
}

char *make_name(char *name)
{
	char *new_name;
	new_name = (char *) calloc(1, strlen(name));
	for(int i=0; i<strlen(name); i++)
	name[i] == ' ' ? new_name[i] = '_' : new_name[i] = name[i];
	return new_name;
}


int main(int argc, char **argv) 
{

	DIR *dir;
	struct dirent *ent;
	struct stat sb;
	bool find = false;

	if ((dir = opendir(".")) == NULL) {
        	fprintf(stderr, "Failed to open . : %s\n", strerror(errno));
        	return 1;
	}
    
	while ((ent = readdir(dir))) {
		if (stat(ent->d_name, &sb)) {
			fprintf(stderr, "Stat failed %s: %s\n", ent->d_name, strerror(errno));
            	return 1;
		}
		if ((sb.st_mode & S_IFMT) == S_IFREG) {
			if(has_spaces(ent->d_name)) {
				find = true;
			 	printf("RENAMING:\t%s   ->   %s\n", ent->d_name, make_name(ent->d_name));
				rename(ent->d_name, make_name(ent->d_name));
			}
        	}
	}
	closedir(dir);
	if(!find) printf("Nothing to do, exiting.\n");
	return 0;
}















